"""
LBRY Recipes plugin for FastLBRY Terminal. Adds commands to find markdown recipe files on the LBRY network.
Copyright (C) 2021  vertbyqb

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

from flbry.variables import *
from subprocess import *
from flbry import url
from flbry import search

def recipe_search(command, args):
    """Search for a recipe on LBRY"""

    # TODO: search.simple() does not support searching without a string. Once it does searching for recipes by their tags should be added.
    tags = ["markdown-recipe"]

    if " " in args:
        search.simple(command[command.find(" ")+1:], tags=tags)
    else:
        search.simple(tags=tags)

def top_recipes(command, args):
    """Gets the trending publications on the LBRY network that have the "markdown-recipe" tag"""

    w, h = tsize()
    
    page_size = h - 5
    page = 1
    
    while True:

        # Printing the search query and page number
        center("TRENDING RECIPES PAGE :"+str(page))

        out = check_output(["flbry/lbrynet",
                    "claim", "search",
                    '--page='+str(page),
                    '--page_size='+str(page_size),
                    "--no_totals",
                        "--order_by=trending_mixed",
                        '--media_types=text/markdown',
                        "--all_tags=markdown-recipe"])

        # Now we want to parse the json
        try:
            out = json.loads(out)
        except:
            print("   Connect to LBRY first.")
            return

        d = {"categories":["Type", "Channel",  "Title"],
                          "size":[1,1,5],
                          "data":[]}
        
        try:
            

            # List what we found
            for n, i in enumerate(out["items"]):
                
                title = "---!Failed Loading Title---"
                ftype = "claim"
                bywho = "[anonymous]"
                
                try:
                    try:
                        title = i["value"]["title"]
                    except:
                        title = i['name']
                    try:
                        ftype = what[i["value"]["stream_type"]]
                    except:
                        ftype = what[i["value_type"]]
                    bywho = i["signing_channel"]["name"]
                except:
                    pass
                
                d["data"].append([ftype, bywho, title])

            table(d)
            
            # Tell the user that he might want to load more
            center("---type 'more' to load more---")
            page = page +1
            
        # Error messages    
        except Exception as e:
            if "code" in out:
                print("    Error code: ", out["code"]  )
                if out["code"] == -32500:
                    print("   SDK is still starting. Patience!")
            else:
                print("    Error :", e)
            return

        # Making sure that we stop every time a new page is reached
        c =  input(typing_dots())
        if c != "more":
            break
    try:
        c = int(c)
    except:
        return

    while True:
        url.get(out["items"][c]["canonical_url"])
        c =  input(typing_dots())
        if not c:
            break
        try:
            c = int(c)
        except:
            return

def inject_help(args):
    """Injects plugin help into applicable files"""
    # SPDX-License-Identifier: GPL-3.0-or-later
    # Copyright (c) vertbyqb 2021
    # You can use this in your plugin. Just change the files and strings arrays and you're good to go.

    files = ["help/main.md"]
    strings = ["""
**recipes**

Will show you a list of trending recipes.

**recipe_search**

Allows you to search for recipes.
"""]

    for n, file in enumerate(files):
        if args[0] == file:
            args[1] = args[1] + strings[n]

    return args

# This is the data that the plugin module reads. 
plugin_data = {
    "title":"LBRY Recipes",
    "author":"vertbyqb",
    "license":"GPL-3.0-or-later",
    "flbry": "terminal",
    "functions":[
        {
            "command": "recipes",
            "main": top_recipes
        },
        {
            "command": "recipe_search",
            "main": recipe_search
        },
        {
            "command": False,
            "flbry.markdown.draw": inject_help
        }
    ]
}
